import {
  commonToastOpt_noIcon,
  CURRENT_USER_KEY,
  passFormCheck,
  phone_verify_rule,
  ROUTER_OBJ,
  TOAST_DURATION,
  TOKEN_key,
  uniNavigate,
  uniShowToast,
} from '../../util/misc';
import {
  ONLINE_SERVER_ADDRESS_BASE,
  tokenRequest,
  uniRequest,
} from '../../util/network';
import { uniSetStorageSync, uniSwitchTab } from '../../util/funcs';
import { TESTING, TestUserData } from '../../util/test';
import { chatMixin } from '../../util/reuse/chatMixin';
import {
  failCbObject,
  uniHideLoading,
  uniShowLoading,
} from '../../util/commonFuncs';
import { USER_ORIENTED } from '../../util/config';

function testCode() {
  if (TESTING) {
    if (USER_ORIENTED) {
      return '1234';
    } else {
      return 'mta';
    }
  }
  return '';
}
export const loginMixin = {
  mixins: [chatMixin],
  data() {
    return {
      requesting: false,
      /**
       *  允许发送, 会间隔60秒才会重新允许发送,
       * true, 不允许发送, false 允许发送
       */
      noSend: false,
      readSecond: 0,
      temTimer: null,
      aForm: {
        phone: TestUserData().phone,
        code: testCode(),
        password: TestUserData().password,
        passwordAgain: TestUserData().password,
      },
      protocolAgreed: TESTING,
    };
  },
  methods: {
    toRegisterWithoutWechat() {
      uniSetStorageSync(ROUTER_OBJ, undefined);
      uniNavigate('/login/register');
    },
    agreeProtocol() {
      this.protocolAgreed = !this.protocolAgreed;
    },
    //  不允许重复发
    setNoRepeatMessage(remainingSeconds) {
      this.noSend = true;
      this.readSecond = remainingSeconds || 60;
      clearInterval(this.temTimer);
      this.temTimer = setInterval(() => {
        if (this.readSecond > 0) {
          this.readSecond--;
        } else {
          clearInterval(this.temTimer);
        }
      }, 1000);
      setTimeout(() => {
        this.noSend = false;
        uniHideLoading(); // 保险一点
      }, this.readSecond * 1000);
    },
    dealWithSuccessSentMessage(responseData) {},
    // 获取验证码
    getVerifyCode(url, baseUrl, requireToken) {
      if (this.noSend) return;
      uniShowLoading('请求短信中');
      let finalUrl;
      // 招商端, 需要手机号和密码才能获取
      if (!USER_ORIENTED) {
        if (!this.aForm.phone || !this.aForm.password) {
          uniShowToast('请先输入电话号码和密码', true, {
            duration: TOAST_DURATION + 2000,
          });

          return;
        }
      }

      if (!USER_ORIENTED) {
        // 招商端,
        finalUrl = ONLINE_SERVER_ADDRESS_BASE + '/adm/captcha/login';
      } else {
        finalUrl = ONLINE_SERVER_ADDRESS_BASE + baseUrl + url;
      }

      // console.log('requesting url :', finalUrl);

      let callbackOpt = {
        success: ({ data }) => {
          uniHideLoading();
          // console.log('发送res', data);
          if (data.code === 200) {
            //发送请求成功
            // data.msg += '。60s内无法再次发送';
            this.setNoRepeatMessage();
            uni.showToast({
              ...commonToastOpt_noIcon(),
              title: data.msg,
            });
          } else {
            // 发送请求不成功
            if (data.msg.indexOf('秒后发送验证码') !== -1) {
              let seconds = parseInt(data.msg.replace(/[^0-9]/gi, ''));
              this.setNoRepeatMessage(seconds);
            }
            uni.showToast({
              ...commonToastOpt_noIcon(),
              title: data.msg,
            });
          }
        },
        fail: (res) => {
          // console.log(res);
          uniShowToast('请求接口失败');
          uniHideLoading();
        },
      };

      if (requireToken) {
        tokenRequest('', this.aForm, {
          url: finalUrl,
          ...callbackOpt,
        });
      } else {
        // console.log('lys', this.aForm);
        uniRequest('', this.aForm, {
          ...callbackOpt,
          url: finalUrl,
        });
      }
    },
    login(dataOpt) {
      if (this.requesting) return; // 不给重复按
      if (!passFormCheck(dataOpt, phone_verify_rule)) return;
      if (!this.protocolAgreed) {
        uni.showToast({
          title: '请先勾选同意相关协议',
          duration: TOAST_DURATION,
          icon: 'none',
        });
        return;
      }
      uniShowLoading('登陆中');
      // console.log('登陆中 opt: ', dataOpt);
      // delete dataOpt.passwordAgain;

      // return;
      uniRequest('/login', dataOpt, {
        success: ({ data }) => {
          uniHideLoading();
          if (data.code === 200) {
            // 登陆成功
            this.requesting = false;

            // console.log('登录数据:  ', data);
            // 登录成功后的操作
            opAfterLoginSuccess(data, data.msg);
          } else {
            uni.showToast({
              title: data.msg,
              duration: TOAST_DURATION,
              icon: 'none',
            });
          }
        },
        ...failCbObject(),
      });
    },
  },
  computed: {
    seconds() {
      if (this.readSecond > 0) {
        return '(' + this.readSecond + ')';
      } else {
        return '';
      }
    },
  },
  mounted() {},

  beforeDestroy() {
    clearInterval(this.temTimer);
  },
};

/**
 * 登录成功后的操作,
 * @description: 仅用于用户端
 * @param data
 * @param toastMsg
 */
export function opAfterLoginSuccess(data, toastMsg) {
  uniShowToast(toastMsg);
  // console.log('登录成功 data:', data);
  uniSetStorageSync(TOKEN_key, data.token); // token 单独存放
  uniSetStorageSync(CURRENT_USER_KEY, data.user_info);
  // 应用初始化
  uni.$emit('appInitialize');

  setTimeout(() => {
    uniSwitchTab('/home/home');
  }, TOAST_DURATION);
}
